package com.yangrd.helper.crudhelper.common.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * description: ReflectionUtils
 *
 * @author: yangrd
 * @date: 2020/9/15
 * @version: 1.0
 */
public class ReflectionUtils {

    public static List<Field> listAllField(Class<?> clazz) {
        List<Field> fieldList = new ArrayList<>();
        /*Stack<Class> classStack = new Stack<>();
        while (!clazz.equals(Object.class)){
            classStack.push(clazz);
            clazz = clazz.getSuperclass();
        }
        while (!classStack.isEmpty()){
            Class aClass = classStack.pop();
            fieldList.addAll(Arrays.asList(aClass.getDeclaredFields()));
        }*/
        while (!clazz.equals(Object.class)) {
            fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
            clazz = clazz.getSuperclass();
        }
        return fieldList;
    }

    public static List<Field> listAllAnnotationField(Class<?> clazz, Class<? extends Annotation> annotation) {
        return listAllField(clazz).stream().filter(field -> field.isAnnotationPresent(annotation)).collect(Collectors.toList());
    }

    public static boolean hasMethods(Class<?> clazz, String methodName) {
        try {
            clazz.getMethod(methodName);
        } catch (NoSuchMethodException e) {
            return false;
        }
        return true;
    }


    public static Optional<Field> getFiled(Class<?> clazz, String filedName) {
        return listAllField(clazz).stream().filter(field -> field.getName().equals(filedName)).findFirst();
    }

    public static Object getMethodReturnVal(Class<?> clazz, String methodName, Object obj) {
        try {
            Method method = clazz.getMethod(methodName);
            return method.invoke(obj);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object getFieldVal(Field field, Object obj) {
        try {
            field.setAccessible(true);
            return field.get(obj);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
